package com.yjr.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yjr.common.constant.ProductConstant;
import com.yjr.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.yjr.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.yjr.gulimall.product.entity.AttrGroupEntity;
import com.yjr.gulimall.product.entity.CategoryEntity;
import com.yjr.gulimall.product.service.AttrAttrgroupRelationService;
import com.yjr.gulimall.product.service.AttrGroupService;
import com.yjr.gulimall.product.service.CategoryService;
import com.yjr.gulimall.product.vo.AttrRespVO;
import com.yjr.gulimall.product.vo.AttrVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjr.common.utils.PageUtils;
import com.yjr.common.utils.Query;

import com.yjr.gulimall.product.dao.AttrDao;
import com.yjr.gulimall.product.entity.AttrEntity;
import com.yjr.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import static com.yjr.common.constant.ProductConstant.AttrEnum.ATTR_TYPE_BASE;
import static com.yjr.common.constant.ProductConstant.AttrEnum.ATTR_TYPE_SALE;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void  saveAttr(AttrVO attrVO) {

        //先把数据保存到pms_attr
        AttrEntity attrEntity=new AttrEntity();
        BeanUtils.copyProperties(attrVO,attrEntity);
        this.save(attrEntity);
        if(attrEntity.getAttrType()== ATTR_TYPE_BASE.getCode() && attrVO.getAttrGroupId()!=null) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attrVO.getAttrGroupId());
            attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
        }
    }

    @Override
    @Transactional
    public PageUtils queryBaseAttrPage(Map<String, Object> params,String type, Long cateLogId) {

        QueryWrapper<AttrEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("attr_type",type.equalsIgnoreCase("sale")?ATTR_TYPE_SALE.getCode(): ATTR_TYPE_BASE.getCode());
        if(cateLogId!=0){
            queryWrapper.eq("catelog_id",cateLogId);
        }
        String key=(String)params.get("key");
        if(StringUtils.isNotEmpty(key)){
            queryWrapper.and((attrEntityQueryWrapper -> {
                attrEntityQueryWrapper.eq("attr_id",key).or()
                        .like("attr_name",key);
            }));
        }
        //分页查询
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
               queryWrapper
        );

        //封装 groupName;
        // catelogName;
        PageUtils pageUtil=new PageUtils(page);
        Map<Long, List<CategoryEntity>> categoryMap = categoryService.list().stream().collect(Collectors.groupingBy(CategoryEntity::getCatId));
        if(!CollectionUtils.isEmpty(page.getRecords())){
            List<AttrRespVO> attrRespVOS = page.getRecords().stream().map(attrEntity -> {
                AttrRespVO attrRespVO = new AttrRespVO();
                BeanUtils.copyProperties(attrEntity, attrRespVO);
                List<CategoryEntity> categoryEntityList = categoryMap.get(attrEntity.getCatelogId());
                if(!CollectionUtils.isEmpty(categoryEntityList)){
                    attrRespVO.setCatelogName(categoryEntityList.get(0).getName());
                }
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (attrAttrgroupRelationEntity != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupService.getOne(new QueryWrapper<AttrGroupEntity>().eq("attr_group_id", attrAttrgroupRelationEntity.getAttrGroupId()));
                    attrRespVO.setGroupName(attrGroupEntity.getAttrGroupName());
                }
                return attrRespVO;
            }).collect(Collectors.toList());
            pageUtil.setList(attrRespVOS);
        }

        return pageUtil;
    }

    @Override
    public AttrRespVO getAttrInfo(Long attrId) {
        AttrRespVO attrRespVO=new AttrRespVO();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,attrRespVO);
        if(attrEntity.getCatelogId()!=null || attrEntity.getCatelogId()!=0){
            Long[] cateLogPath = categoryService.findCateLogPath(attrEntity.getCatelogId());
            attrRespVO.setCatelogPath(cateLogPath);
        }
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
        if(attrAttrgroupRelationEntity!=null){
            AttrGroupEntity group = attrGroupService.getById(attrAttrgroupRelationEntity.getAttrGroupId());
            if(group!=null){
                attrRespVO.setAttrGroupId(group.getAttrGroupId());
                attrRespVO.setGroupName(group.getAttrGroupName());
            }
        }

        return attrRespVO;
    }

    @Override
    public void updateAttr(AttrVO attr) {

        AttrEntity attrEntity=new AttrEntity();

        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        if(attrEntity.getAttrType()==ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId()!=null){
            //更新分组关联表
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity=new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());

            QueryWrapper<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityQueryWrapper = new QueryWrapper<>();

            attrAttrgroupRelationEntityQueryWrapper.eq("attr_id",attr.getAttrId());
            Integer count = attrAttrgroupRelationDao.selectCount(attrAttrgroupRelationEntityQueryWrapper);

            if(count>0){
                attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));

            }
            else {
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }
    }

    @Override
    public List<AttrEntity> getAttrRelationList(Long attrgroupId) {

        //根据属性分组Id查询属性集合
        List<AttrAttrgroupRelationEntity> attrgroupRelationEntities = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        if(!CollectionUtils.isEmpty(attrgroupRelationEntities)){
            List<Long> attrIds = attrgroupRelationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

            List<AttrEntity> attrEntities = new ArrayList<>(this.listByIds(attrIds));
            return  attrEntities;
        }
        return null;
    }

    @Override
    public PageUtils  getAttrGroupRelationList(Long attrgroupId,Map<String, Object> params) {
        AttrGroupEntity groupEntity = attrGroupService.getById(attrgroupId);
        QueryWrapper<AttrEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("catelog_id",groupEntity.getCatelogId());
        queryWrapper.eq("attr_type",ATTR_TYPE_BASE.getCode());
       String  key = (String) params.get("key");
       if(StringUtils.isNotEmpty(key)){
           queryWrapper.and(attrEntityQueryWrapper -> {
               attrEntityQueryWrapper.eq("attr_id",key).or().eq("attr_name",key);
           });
       }
        IPage<AttrEntity> attrEntityIPage = this.page(new Query<AttrEntity>().getPage(params),queryWrapper);
        PageUtils pageUtils=new PageUtils(attrEntityIPage);

        List<AttrEntity> attrEntities = attrEntityIPage.getRecords();
        if(!CollectionUtils.isEmpty(attrEntities)){

            //查询当前分类下面的所有分组ID
            List<AttrGroupEntity> attrGroupEntities = attrGroupService.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", groupEntity.getCatelogId()));
            List<Long> groupIds = attrGroupEntities.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());
            //获取分组关联表信息
            List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<>());
            if(!CollectionUtils.isEmpty(attrAttrgroupRelationEntities)){
                List<Long> attrIdsHasRelation = attrAttrgroupRelationEntities.stream().filter(attrAttrgroupRelationEntity -> groupIds.contains(attrAttrgroupRelationEntity.getAttrGroupId())).map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

                if(attrIdsHasRelation.size()>0){
                    attrEntities=attrEntities.stream().filter(attrEntity -> !attrIdsHasRelation.contains(attrEntity.getAttrId())).collect(Collectors.toList());
                }


            }

            pageUtils.setList(attrEntities);
        }
        return pageUtils;
    }

    @Override
    public List<Long> listSearchAttrs(List<Long> attrIds) {

        return baseMapper.listSearchAttrs(attrIds);
    }

    /*
    这种思路也OK，但我希望你有自己的想法
    @Override
public PageUtils getOtherAttrs(Map<String, Object> params, int attrgroupId) {
    //根据分组得到三级分类id，然后查询出该三级分类下所有分组已经关联好的属性
    Long catelogId = attrGroupDao.selectById(attrgroupId).getCatelogId();
    List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id",
            catelogId));
    List<Long> attrGroupIds = group.stream().map(AttrGroupEntity::getAttrGroupId).collect(toList());
    List<AttrAttrgroupRelationEntity> relationEntities =
            attrAttrgroupRelationDao.selectList(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrGroupIds));
    //三级分类下所有分组对应的属性id集合
    //所以那些没有分组的属性就是可以额外添加的
    List<Long> attrIds = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(toList());

    QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
            .eq("catelog_id", catelogId)
            .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
    if (attrIds != null && attrIds.size() > 0) {
        wrapper.notIn("attr_id", attrIds);
    }
    String key = (String) params.get("key");
    if (StringUtils.isNotEmpty(key)) {
        wrapper.and(item -> item.eq("attr_id", key).or().like("attr_name", key));
    }
    IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
    return new PageUtils(page);
}

     */
}